<template>
  <div v-if="!isPageLoading">
    <div class="cartoon-content">
      <div class="cartoon-box">
        <div class="img-box">
          <ImageCache
            :url="courseData.titleImg"
            :record="courseData"
          ></ImageCache>
          <span
            :class="courseData.lastDetailsNameV === '完' ? 'status' : 'status1'"
          >
            {{ courseData.lastDetailsNameV }}
          </span>
        </div>
        <div class="cartoon-infor">
          <div class="titile">
            <h4>{{ courseData.title }}</h4>
            <p>{{ courseData.authorName }}</p>
          </div>
          <div class="date">
            <div style="text-align: left">
              <h5
                v-if="courseData.viewCounts"
                v-html="
                  courseData.viewCounts >= 10000
                    ? `${((courseData?.viewCounts * 3) / 10000).toFixed(
                        2
                      )}<span>万人</span>`
                    : `${courseData?.viewCounts * 3}<span>人</span>`
                "
              ></h5>
              <h5 v-else>0<span>人</span></h5>
              <p>推荐分享</p>
            </div>
            <div style="text-align: right">
              <h5
                v-if="courseData.viewCounts"
                v-html="
                  courseData?.viewCounts >= 10000
                    ? `${(courseData?.viewCounts / 10000).toFixed(
                        2
                      )}<span>万人</span>`
                    : `${courseData?.viewCounts}<span>人</span>`
                "
              ></h5>
              <h5 v-else>0<span>人</span></h5>
              <p>正在阅读</p>
            </div>
          </div>
        </div>
      </div>
      <div class="btn-list">
        <div
          class="btn"
          :class="courseData.isCollect == 1 ? 'yishou' : 'shou'"
          @click="getCourseCollect"
        >
          <p v-show="courseData.isCollect == 0"><span>+</span>添加收藏</p>
          <p v-show="courseData.isCollect == 1">取消收藏</p>
        </div>

        <div v-if="readInfo.courseDetailsId" class="btn read" @click="getLooks">
          <p>继续阅读</p>
        </div>
        <div v-else class="btn read" @click="getLooks">
          <p>立即阅读</p>
        </div>
      </div>
    </div>
    <t-tabs v-model="tabsValue" theme="card" @change="onChangeTab">
      <t-tab-panel value="1" label="漫画">
        <div class="cartoon-det">
          <!-- <h4 class="title-mh">漫画</h4> -->
          <div class="tag-list">
            <span
              v-for="(item, index) in courseData.courseClassification"
              :key="item.id"
              @click="getTag(item)"
              >{{ item.classificationName }}</span
            >
          </div>
          <div class="cartoon-text">
            <p>{{ courseData.details }}</p>
          </div>
          <!-- <div class="read" @click="getLooks">
				立即阅读
			</div> -->
          <p style="text-align: left">更新：{{ courseData.updateTime }}</p>
          <div class="chapter-list">
            <span
              v-for="(item, index) in getChapterList"
              :key="index"
              @click="getlook(item, index)"
              :class="getClassName(item.courseDetailsName)"
            >
              {{ item.courseDetailsName }}</span
            >
          </div>
          <!-- <t-grid :column="4" class="grid-demo">
			    <t-grid-item v-for="(item,index) in getChapterList" :key="index" :text="item.courseDetailsName"/>
			</t-grid> -->
        </div>
      </t-tab-panel>
      <t-tab-panel value="2" label="留言">
        <div class="book-box" @scroll="handleScroll">
          <t-list :async-loading="loadingTxt">
            <t-cell
              v-for="(item, index) in messageList"
              :key="index"
              class="message-item"
              align="middle"
            >
              <div class="head-box">
                <t-image class="img" :src="item.userAvatar"></t-image>
              </div>
              <div class="info">
                <div class="name">{{ item.userName }}</div>
                <div class="txt">{{ item.content }}</div>
                <div class="time">{{ item.createTime }}</div>
              </div>
            </t-cell>
          </t-list>
        </div>
      </t-tab-panel>
    </t-tabs>

    <!-- <DownloadApk :isShowDialog.sync="isShowDialog"  /> -->
    <div v-if="tabsValue == '2'" class="fixed-box">
      <div class="input-box">
        <t-input v-model="keyTxt" placeholder="请输入文字" />
      </div>
      <div :class="`btn ${keyTxt ? 'isuse' : ''}`" @click="onSubmitTxt">
        发表
      </div>
    </div>
  </div>
  <div v-else>
    <PageLoading :is-loading="isPageLoading"></PageLoading>
  </div>
</template>

<script setup>
import { onMounted, ref, reactive, nextTick, toRefs, toRaw } from "vue";
import { useRouter } from "vue-router";
import { getCourseDet, getChapter } from "@/api/index.js";
import { getReadRecord } from "@/utils/utils";
import { Message } from "tdesign-mobile-vue";
import DownloadApk from "./downloadApk.vue";
import PageLoading from "./PageLoading.vue";
// import logoImage from '/src/assets/logo-h.png'
import logos from "/src/assets/logo.png";
import logoImage from "/src/assets/logo-bai.png";
import logoText from "/src/assets/logo-text.png";
import comicApi from "@/api/comicApi";
import ImageCache from "@/components/ImageCache";
// import { fetchOssTxtToBase64 } from "@/utils/ossTxtToBase64";
let readInfo = ref({});
const router = useRouter();
const tabPanels = [
  {
    value: "1",
    label: "漫画",
  },
  {
    value: "2",
    label: "留言",
  },
];
const isShowDialog = ref(false);
const isShou = ref(false);
// 控制加载动画显示
const isPageLoading = ref(true);
const secretKey = "53841080";
const state = reactive({
  tabsValue: "1",
  loading: false,
  noMore: false,
  keyTxt: "",
  pageData: {
    pageSize: 10,
    pageNum: 1,
    targetId: "",
    targetType: "course",
  },
  messageList: [],
  loadingTxt: "",
  boforeSrcoll: 0,
});
const {
  tabsValue,
  isRefreshing,
  loading,
  noMore,
  keyTxt,
  messageList,
  loadingTxt,
} = toRefs(state);
// 跳转方法
const getDet = () => {
  router.push({
    path: "/det",
  });
};

// 1. 接收父组件传递的参数（Props）
const props = defineProps({
  getId: {
    type: Number,
    default: "默认消息",
  },
});

// 子组件内部状态
const courseData = reactive({});
const getChapterList = ref([]);
const classifyList = ref([]);

const getCourse = async () => {
  try {
    // const id = 143;
    const res = await getCourseDet(props.getId);
    Object.assign(courseData, res.data);
    const classifyData = courseData.classify.split(",");
    const classifyIdArr = courseData.classifyIds.split(",");
    classifyList.value = classifyData.map((text, index) => ({
      text: text,
      id: classifyIdArr[index], // 按索引对应ID
    }));
    isPageLoading.value = false;
  } catch (error) {
    // console.error('数据获取失败', error);
    isPageLoading.value = false;
  }
};
const getChapterDet = async () => {
  try {
    // const id = 143;
    const pamrms = {
      id: props.getId,
      page: 1,
      limit: 20,
      orderType: "asc",
    };
    const date = await getChapter(pamrms);
    getChapterList.value = date.data.records.reverse();
  } catch (error) {
    console.error("数据获取失败", error);
  }
};

const getlook = (item, index) => {
  localStorage.setItem("courseDetailsId", item.courseDetailsId);
  localStorage.setItem("modeType", courseData.modeType);
  router.push({
    name: "det", // 对应路由配置中的 name
    params: {
      id: item.courseId,
    }, // 参数名需与路由中的 :id 一致
  });
};

//根据章节名字长度显示不同的class
const getClassName = (name) => {
  if (name.length <= 5) return "short-name";
  if (name.length <= 9) return "medium-name";
  if (name.length <= 14) return "md-name1";
  if (name.length <= 22) return "md-name";
  return "long-name";
};
const getLooks = () => {
  localStorage.setItem(
    "courseDetailsId",
    getChapterList.value[0].courseDetailsId
  );
  localStorage.setItem("modeType", courseData.modeType);
  router.push({
    name: "det", // 对应路由配置中的 name
    params: {
      id: props.getId,
    }, // 参数名需与路由中的 :id 一致
  });
};

const getTag = (item) => {
  router.push({
    name: "classify", // 对应路由配置中的 name
    params: {
      id: item.classificationId,
    }, // 参数名需与路由中的 :id 一致
  });
};

//收藏、取消收藏
const getCourseCollect = async () => {
  const sendData = {
    courseId: props.getId,
    courseDetailsId: props.getId,
    classify: 1,
    type: courseData.isCollect === 0 ? 1 : 0,
  };
  const result = await comicApi.insertCourseCollect(sendData);
  if (result.code === 0) {
    courseData.isCollect = !courseData.isCollect;
    // isShou.value = !isShou.value
  }
};
// 提交留言
async function onSubmitTxt() {
  if (state.keyTxt) {
    const data = await comicApi.saveComment({
      targetId: props.getId,
      userId: localStorage.getItem("userInfo")
        ? JSON.parse(localStorage.getItem("userInfo")).userId
        : "",
      isAnonymous: 1,
      content: state.keyTxt,
      targetType: "course",
    });
    if (data.code == 0) {
      state.keyTxt = "";
      state.pageData.pageNum = 1;
      state.messageList = [];
      getMessageList();
    }
    console.log("d", data);
  }
}
function handleScroll(event) {
  const scrollTop = event.target.scrollTop;
  const offsetHeight = event.target.offsetHeight;
  const scrollHeight = event.target.scrollHeight;
  if (state.boforeSrcoll <= scrollTop) {
    state.boforeSrcoll = scrollTop;
  }
  if (
    scrollHeight - (offsetHeight + scrollTop) <= 10 &&
    state.boforeSrcoll <= scrollTop
  ) {
    if (!state.loading) {
      state.loading = true;
      state.pageData.pageNum++;
      getMessageList();
    }
  }
}
// 页面滚动到底部
function onScroll(scrollBottom) {}
// 获取留言页面
async function getMessageList() {
  state.pageData.targetId = props.getId;
  state.loadingTxt = "加载中....";
  try {
    const result = await comicApi.getCommentList(toRaw(state.pageData));
    console.log("result", result);
    setTimeout(() => {
      state.loading = false;
    }, 300);
    state.loadingTxt = "";
    if (result.code == 0) {
      state.messageList = state.messageList.concat(result.data.records);
    }
  } catch {
    setTimeout(() => {
      state.loading = false;
    }, 300);
    state.loadingTxt = "";
  }
}
// 选项卡点击
function onChangeTab() {
  if (state.tabsValue == "2") {
    state.pageData.pageNum = 1;
    state.messageList = [];
    state.boforeSrcoll = 0;
    getMessageList();
  }
}
onMounted(async () => {
  getCourse();
  getChapterDet();
  readInfo.value = getReadRecord(props.getId);
});
</script>

<style scoped lang="scss">
:deep(.t-tabs__item-inner) {
  font-size: 16px;
}
:deep(.t-tabs__item--active) {
  --td-tab-item-active-color: $b10-color;
}
:deep(.t-cell__note) {
  align-items: flex-start;
}
:deep(.t-cell) {
  &::after {
    border: none;
  }
}
.cartoon-content {
  padding: 15px;
  display: flex;
  flex-direction: column;
  align-items: center;
  // background-image: url(../assets/bj2.webp);
  // background-repeat: no-repeat;
  // background-size: 100% 108%;
  padding-bottom: 32px;

  .cartoon-box {
    display: flex;
    align-items: flex-start;
    justify-content: flex-start;
    width: 100%;

    .cartoon-infor {
      margin-left: 20px;
      color: #303133;
      // text-align: left;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      width: calc(100% - 123px);
      height: 152px;
      align-items: flex-start;
      margin-top: 8px;

      .titile {
        text-align: left;

        h4 {
          font-size: 18px;
          font-weight: 700;
          position: relative;
          color: #fff;
          top: -4px;
          width: 100%;
          // white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 3;
          -webkit-box-orient: vertical;
          line-height: 24px;
        }

        p {
          // font-size: 18px;
          font-size: 14px;
          margin-top: 5px;
          color: #4b87ff;
        }
      }

      .date {
        display: flex;
        width: 100%;
        position: relative;
        bottom: -4px;

        div {
          width: 50%;
          text-align: center;

          h5 {
            // font-size: 26px;
            font-size: 18px;
            font-weight: 700;
            color: #fff;

            span {
              font-size: 16px;
            }
          }

          p {
            // font-size: 16px;
            position: relative;
            top: -2px;
            font-size: 13px;
            color: #999999;
            font-weight: 550;
          }
        }
      }
    }
  }
}

.img-box {
  border-radius: 6px;
  // overflow: hidden;
  position: relative;
  width: 108px;
  height: 152px;
  margin-top: 8px;
  z-index: 999;

  // height: 127px;
  &::before {
    content: "";
    position: absolute;
    top: -4px; // 向上偏移，露出层次感
    left: 4px; // 向左偏移
    width: calc(100% - 8px); // 比容器宽，覆盖更多区域
    height: calc(100% - 8px); // 比容器高
    background: rgba(234, 197, 176, 1); // 金色渐变
    // opacity: 0.3; // 透明度，模拟“背后层”的朦胧感
    border-radius: 6px; // 圆角与容器匹配
    z-index: -1; // 放在容器下方
    // transform: rotate(-2deg); // 轻微旋转，增强层次
  }

  // 第二层金色背板（::after）
  &::after {
    content: "";
    position: absolute;
    top: -8px; // 偏移量小于 before，模拟“前一层”
    left: 8px;
    width: calc(100% - 16px);
    height: calc(100% - 16px);
    background: rgba(247, 233, 225, 1);
    // opacity: 0.2; // 透明度更低，更靠后
    border-radius: 6px;
    z-index: -2; // 放在 before 下方
    // transform: rotate(1deg); // 不同旋转角度，增强错落感
  }

  .status {
    position: absolute;
    top: 3px;
    right: 3px;
    color: #ff0000;
    font-weight: 500;
    text-shadow: 0 0 2px #fff, /* 轻微模糊使边缘更平滑 */ -1px -1px 0 #fff,
      -1px 0 0 #fff, -1px 1px 0 #fff, 0 -1px 0 #fff, 0 1px 0 #fff,
      1px -1px 0 #fff, 1px 0 0 #fff, 1px 1px 0 #fff;
  }

  .status1 {
    position: absolute;
    top: 3px;
    right: 3px;
    color: #409eff;
    font-weight: 500;
    text-shadow: 0 0 2px #fff, /* 轻微模糊使边缘更平滑 */ -1px -1px 0 #fff,
      -1px 0 0 #fff, -1px 1px 0 #fff, 0 -1px 0 #fff, 0 1px 0 #fff,
      1px -1px 0 #fff, 1px 0 0 #fff, 1px 1px 0 #fff;
  }
}

.cartoon-det {
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
  overflow: hidden;
  padding-left: 15px;
  padding-right: 0;
  padding-bottom: 20px;
  background-color: #fff;

  // position: relative;
  // top: -15px;
  .title-mh {
    font-size: 16px;
    color: #000000;
    font-weight: 600;
    margin-top: 10px !important;
    width: 100%;
    position: relative;
    left: -7.5px;
    display: inline-block;
  }

  .tag-list {
    display: flex;
    // align-items: center;
    justify-content: flex-start;
    flex-wrap: wrap;
    gap: 5px; // 标签之间的间距（水平+垂直）
    // padding-right: 20px;
    margin-bottom: 20px;
    padding-top: 15px;

    span {
      display: block;
      // width: calc(20% - 10px);
      // height: 20px;
      // width: calc(14% - 0.5px);
      padding: 6.5px 11.5px;
      // margin-right: 10px;
      text-align: center;
      line-height: 20px;
      border-radius: 4px;
      background-color: #f8e6d1;
      font-size: 14px;
      color: #986d59;
      // margin-bottom: 10px;
    }
  }

  .cartoon-text {
    padding-right: 15px;

    p {
      font-size: 14px;
      line-height: 25px;
      text-align: left;
      margin-bottom: 5px;
    }
  }

  .chapter-list {
    display: flex;
    // align-items: center;
    justify-content: flex-start;
    flex-wrap: wrap;
    margin-top: 24px;
    gap: 10px; // 标签之间的间距（水平+垂直）

    // padding-right: 15px;
    span {
      display: block;
      height: 32px;
      text-align: center;
      line-height: 32px;
      border-radius: 20px;
      font-size: 14px;
      font-weight: 600;
      border: 1px solid rgba(187, 187, 187, 1);
    }

    .short-name {
      width: calc(25% - 13px);
    }

    .medium-name {
      width: calc(33.33% - 13px);
    }

    .md-name1 {
      width: calc(50% - 13px);
    }

    .md-name {
      width: calc(75% - 13px);
    }

    .long-name {
      width: calc(100% - 13px);
    }
  }

  .read {
    width: calc(100% - 15px);
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 15px;
    font-weight: 600;
    border-radius: 50px;
    background: linear-gradient(to right, #fdda28, #f1b444);
    margin-top: 20px;
    margin-bottom: 10px;
  }
}

.logo-box {
  background-color: #fff;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  position: absolute;
  bottom: 15px;
  // left: calc(50% - 100px);
  width: 100%;
}

.btn-list {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  margin-top: 25px;

  .btn {
    width: 42%;
    height: 42px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 25px;

    p {
      width: 80%;
      display: inline-block;
      text-align: center;

      span {
        font-size: 20px;
        display: inline-block;
        position: relative;
        top: 3px;
      }
    }
  }

  .shou {
    border: 1px solid #f1b444;
    color: #f1b444;
  }

  .read {
    background: linear-gradient(to right, #fdda28, #f1b444);
    color: #303133;
  }

  .yishou {
    border-color: transparent !important;
    color: #f1b444 !important;
    height: 44px;
  }
}
.book-box {
  height: calc(100vh - 427px);
  overflow: auto;
  .message-item {
    display: flex;
    align-items: flex-start;
    justify-content: flex-start;
    padding-top: 10px;
    .head-box {
      padding: 0 10px;
      .img {
        width: 30px;
        height: 30px;
        display: block;
        border-radius: 50%;
        overflow: hidden;
      }
    }
    .info {
      border-bottom: 1px solid $be9-color;
      flex: 1;
      text-align: left;
      .name {
        font-size: 14px;
        color: $b6c-color;
      }
      .txt {
        font-size: 15px;
        font-weight: 700;
        color: $b10-color;
      }
      .time {
        font-size: 14px;
        color: $be9-color;
      }
    }
  }
}
.fixed-box {
  position: fixed;
  left: 0;
  bottom: 0;
  right: 0;
  z-index: 999;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  padding: 10px 15px;
  background-color: #fff;
  border-top: 1px solid #e9e9e9;
  .input-box {
    flex: 1;
    padding-right: 10px;
    box-sizing: border-box;
    :deep(.t-input) {
      background-color: #e6e6e6;
      border-radius: 50px;
      padding: 6px 15px;
      font-size: 15px;
    }
  }
  .btn {
    width: 70px;
    height: 36px;
    text-align: center;
    line-height: 36px;
    background-color: #e6e6e6;
    font-size: 16px;
    font-style: normal;
    font-weight: 750;
    color: $b6c-color;
    border-radius: 50px;
    &.isuse {
      background: linear-gradient(90deg, #fdda28 0%, #f1b444 100%);
      color: $b10-color;
    }
  }
}
</style>
